package com.example.wss65.jumpball_test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.example.wss65.jumpball_test.particle.Part;
import com.example.wss65.jumpball_test.particle.ParticleGen;
import com.example.wss65.jumpball_test.particle.ParticleSys;
import com.example.wss65.jumpball_test.particle.Particleable;

import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {

    private int myHeight;       //自己窗口高度
    private int myWidth;        //自己窗口宽度
    int textsize = 100;
    int aColor = 80;             //a层涟漪透明色
    int aColorA;             //a层涟漪透明色
    int bColor = 50;             //b层涟漪透明色
    int bColorB;             //b层涟漪透明色
    float myBall_Size = 80;     //球的大小
    float tm_balla = 80;        //a层涟漪
    float tm_ballb = 80;        //b层涟漪
    float myBall_Speed = 50;     //球的运动速度
    float myBall_Up = 3000;      //球的上升速度
    float myBall_X;             //球的X
    volatile float myBall_Y;    //球的Y
    float aPost_Height;         //柱子a的高
    float bPost_Height;         //柱子b的高
    float aPost_Width = 100;    //柱子a的宽
    float bPost_Width = 100;    //柱子b的宽
    float aPost_X;              //柱子a的X；
    float aPost_Y;              //柱子a的Y；
    float bPost_X;              //柱子b的X；
    float bPost_Y;              //柱子b的Y；
    float post_Speed;           //柱子运动速度
    int myScore = 0;            //我的分数；
    boolean myOver = false;     //判断游戏是否结束

    //    int myLife;                 //我的生命
    MyGameView myGameView;      //图层绘制
    private volatile float targetY;
    private final Random randomor;
    private int postLacunaHeight = 600;
    private int postMinHeight = 150;

    ArrayList<Part> arrPart;
    ArrayList<Particleable> psys = new ArrayList<>();
    ArrayList<Particleable> rm_list = new ArrayList<>();

    public MainActivity() {
        randomor = new Random((long) (Math.random() * 0xf0000000000L));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //获取自己创建的视图实例
        myGameView = new MyGameView(this);

        arrPart = ParticleGen.Gen(tm_balla, 2, 8, 300);

        setContentView(myGameView);
        //获取窗口的一个管理器
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        //获取屏幕的宽高
        myWidth = metrics.widthPixels;
        myHeight = metrics.heightPixels;
        GameStart();
    }


    @SuppressLint("ClickableViewAccessibility")
    public void GameStart() {
        myOver = false;
        //设置post初始位置
        setPostLocation();
        myScore = 0;
        post_Speed = 10f;
        myBall_Speed = 10f;
        myBall_Up = 3000;
        myBall_X = 400;
        myBall_Y = 1;
        targetY = 100000;
        handler.sendEmptyMessage(0x123);

        final Timer timer = new Timer();

//        final Timer aTimer = new Timer();
//
//        aTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                if (myOver == false) {
//                    myOver = false;
//                    GameStart();
//                } else {
//                    myOver = true;
//                    timer.cancel();
//                }
//            }
//        }, 300, 1000);


        timer.schedule(new TimerTask() {
            @Override
            public void run() {


                tm_balla += 0.01f;
//                Log.e("======", String.valueOf(tm_balla));

                if (tm_balla >= 100f) {
                    tm_balla = myBall_Size;
                    aColorA = 50;
                }
                aColorA = (int) (100 - (tm_balla / (100 - aColor)));

                tm_ballb += 0.01f;
                if (tm_ballb >= 130f) {
                    tm_ballb = myBall_Size;
                    bColorB = 0;
                }
                bColorB = (int) (80 - (tm_ballb / (80 - bColor)));


                handler.sendEmptyMessage(0x123);
//                Log.e("===", String.valueOf(myBall_Y) + "   " + myWidth);
                float f_Height = myHeight;
                //柱子到最左边之后
                if (aPost_X <= 0) {
                    setPostLocation();
                    myScore = myScore + 1;
                }

//                //球碰到顶部或者落到底部游戏结束
                if (myBall_Y >= f_Height || myBall_Y <= 0) {
//                    myOver = true;
                    psys.add(new ParticleSys(arrPart, Color.GREEN, myBall_X, myBall_Y, new Runnable() {
                        @Override
                        public void run() {
                            timer.cancel();
                            myOver = true;

                        }
                    }));
                    myBall_Y = myHeight / 2;
                    myBall_X = -1000;


                } else {
                    RectF aPostRect = new RectF(aPost_X, 0, aPost_X + aPost_Width, 0 + aPost_Height);
                    RectF bPostRect = new RectF(bPost_X, bPost_Y, bPost_X + bPost_Width, bPost_Height + bPost_Y);
                    RectF ballRect = new RectF(myBall_X - myBall_Size, myBall_Y - myBall_Size, myBall_X + myBall_Size, myBall_Y + myBall_Size);
                    if (aPostRect.contains(ballRect) || bPostRect.contains(ballRect)
                            || aPostRect.contains(ballRect.right, ballRect.top)
                            || bPostRect.contains(ballRect.right, ballRect.bottom)
                            || aPostRect.contains(ballRect.left, ballRect.top)
                            || bPostRect.contains(ballRect.left, ballRect.bottom)) {
//                    myOver = true;
                        psys.add(new ParticleSys(arrPart, Color.GREEN, myBall_X, myBall_Y, new Runnable() {
                            @Override
                            public void run() {
                                timer.cancel();
                                myOver = true;
                            }
                        }));
                        myBall_Y = myHeight / 2;
                        myBall_X = -1000;


                    }
                }

            }
        }, 0, 16);

    }

    int i = 0;

    private void setPostLocation() {
        aPost_X = myWidth - aPost_Width;
        aPost_Y = 0;
        aPost_Height = randomHeight();

        bPost_X = myWidth - bPost_Width;
        bPost_Y = aPost_Y + aPost_Height + postLacunaHeight;
        bPost_Height = myHeight - bPost_Y;
//        Log.e("================",String.format("myH:%d,aY:%f,aH:%f,bY:%f,bH:%f",myHeight,aPost_Y,aPost_Height,bPost_Y,bPost_Height));
    }

    public int randomHeight() {
        if (postLacunaHeight > (myHeight - 2 * postMinHeight)) {
            postLacunaHeight = postMinHeight;
        }
        int aRHeight = randomor.nextInt(myHeight - (postMinHeight + postLacunaHeight));
        if (aRHeight < postMinHeight)
            return randomHeight();

        return aRHeight;
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x123) {
                myGameView.invalidate();
            }
        }
    };

    class MyGameView extends View {
        Paint paint = new Paint();
        Paint buttonPaint;
        RectF buttonRect, buttSize;

        public MyGameView(Context context) {
            super(context);
            buttSize = new RectF(0, 0, 300, 200);
            buttonPaint = new Paint();
            buttonPaint.setColor(Color.LTGRAY);
            buttonPaint.setAntiAlias(true);
            buttonPaint.setTextSize(30);
        }


        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);


            if (myBall_Y > targetY) {
                myBall_Y -= 10;
            } else if (myBall_Y <= targetY) {
//                    targetY = myHeight;
                //post和ball变化

                myBall_Y += myBall_Speed;
            }

            aPost_X = aPost_X - post_Speed;
            bPost_X = bPost_X - post_Speed;


            paint.setStyle(Paint.Style.FILL);  //设置属性（默认）
            paint.setAntiAlias(true); //是否抗锯齿
            if (myOver) {
                //执行游戏结束后的效果
                //画分数
                paint.setColor(Color.rgb(200, 0, 0));
                paint.setTextSize(100);
                canvas.drawText("游戏结束    得分：" + myScore + "", myWidth / 2 - 450, myHeight / 2 - 200, paint);

//
//                if (myScore <= 20 && myScore > 0) {
//                    paint.setColor(Color.rgb(50, 50, 150));
//                    paint.setTextSize(100);
//                    canvas.drawText("你竟然才跳了" + myScore + "次啊？", myWidth / 2 - 700, myHeight / 2 + 100, paint);
//                } else if (myScore <= 50 && myScore > 20) {
//                    paint.setColor(Color.rgb(50, 50, 150));
//                    paint.setTextSize(100);
//                    canvas.drawText("一般般，才跳了" + myScore + "次，跟我比差的远了。", myWidth / 2 - 800, myHeight / 2 + 100, paint);
//                } else if (myScore <= 100 && myScore > 50) {
//                    paint.setColor(Color.rgb(50, 50, 150));
//                    paint.setTextSize(100);
//                    canvas.drawText("跳了" + myScore + "次，马马虎虎吧。", myWidth / 2 - 500, myHeight / 2 + 100, paint);
//                } else if (myScore > 100) {
//                    paint.setColor(Color.rgb(50, 50, 150));
//                    paint.setTextSize(100);
//                    canvas.drawText("跳了" + myScore + "次，勉强和我比比。", myWidth / 2 - 550, myHeight / 2 + 100, paint);
//                } else if (myScore == 0) {
//                    paint.setColor(Color.rgb(50, 50, 150));
//                    paint.setTextSize(100);
//                    canvas.drawText("懒的说你了，一次都没成功", myWidth / 2 - 550, myHeight / 2 + 100, paint);
//                }
                if (buttonRect == null) {
                    buttonRect = new RectF();
                    buttonRect.left = (myWidth - buttSize.width()) / 2;
                    buttonRect.top = (myHeight - buttSize.height()) / 2 + 400;
                    buttonRect.right = (myWidth + buttSize.width()) / 2;
                    buttonRect.bottom = (myHeight + buttSize.height()) / 2 + 400;
                }
                drawButton(canvas, "重新开始", buttonRect);
            } else {
                //执行游戏进行中的效果

                int color = 0;
                int swc = 0;
                //绘制背景色
                paint.setColor(Color.BLACK);
                if (myScore % 3 == 0) {

                } else {
                    paint.setColor(Color.WHITE);
                }

                canvas.drawRect(0, 0, myWidth, myHeight, paint);
                //画分数
                if (myScore % 3 == 0) {
                    paint.setColor(Color.WHITE);
                } else {
                    paint.setColor(Color.BLACK);

                }
                paint.setTextSize(300);
                canvas.drawText(myScore + "", myWidth / 2 - 150, myHeight / 2, paint);

                //画球
                if ((swc = myScore % 7 + 1) == 1) {
                    color = Color.rgb(123, 11, 99);
                    aColor = Color.argb(aColorA, 123, 11, 99);
                    bColor = Color.argb(bColorB, 123, 11, 99);
                } else if (swc == 2) {
                    color = Color.rgb(255, 183, 255);
                    aColor = Color.argb(aColorA, 255, 183, 255);
                    bColor = Color.argb(bColorB, 255, 183, 255);
                } else if (swc == 3) {
                    color = Color.rgb(255, 255, 170);
                    aColor = Color.argb(aColorA, 255, 255, 170);
                    bColor = Color.argb(bColorB, 255, 255, 170);
                } else if (swc == 4) {
                    color = Color.rgb(123, 56, 11);
                    aColor = Color.argb(aColorA, 123, 56, 11);
                    bColor = Color.argb(50, 123, 56, 11);
                } else if (swc == 5) {
                    color = Color.rgb(32, 11, 123);
                    aColor = Color.argb(aColorA, 32, 11, 123);
                    bColor = Color.argb(bColorB, 32, 11, 123);
                } else if (swc == 6) {
                    color = Color.rgb(102, 123, 11);
                    aColor = Color.argb(aColorA, 102, 123, 11);
                    bColor = Color.argb(bColorB, 102, 123, 11);
                } else if (swc == 7) {
                    color = Color.rgb(255, 0, 208);
                    aColor = Color.argb(aColorA, 255, 0, 208);
                    bColor = Color.argb(bColorB, 255, 0, 208);
                }

                paint.setColor(bColor);
                canvas.drawCircle(myBall_X, myBall_Y, tm_ballb, paint);
                paint.setColor(aColor);
                canvas.drawCircle(myBall_X, myBall_Y, tm_balla, paint);
                paint.setColor(color);
                canvas.drawCircle(myBall_X, myBall_Y, myBall_Size, paint);
                //画上方post

                if ((swc = myScore % 7 + 1) == 1)
                    color = Color.rgb(255, 170, 170);
                else if (swc == 2)
                    color = Color.rgb(255, 140, 170);
                else if (swc == 3)
                    color = Color.rgb(140, 159, 255);
                else if (swc == 4)
                    color = Color.rgb(113, 210, 255);
                else if (swc == 5)
                    color = Color.rgb(113, 255, 175);
                else if (swc == 6)
                    color = Color.rgb(137, 80, 113);
                else if (swc == 7)
                    color = Color.rgb(236, 255, 113);


                paint.setColor(color);
                canvas.drawRect(aPost_X, aPost_Y, aPost_X + aPost_Width, aPost_Y + aPost_Height, paint);
                //画下方post
                canvas.drawRect(bPost_X, bPost_Y, bPost_X + bPost_Width, bPost_Y + bPost_Height, paint);


//                Log.e("====", String.valueOf(bPost_X)+String.valueOf("  ")+String.valueOf(aPost_X));
//                Log.e("====", String.valueOf(bPost_Y)+String.valueOf("  ")+String.valueOf(aPost_Y));
//                Log.e("====", String.valueOf(bPost_X + bPost_Width)+String.valueOf("  ")+String.valueOf(aPost_X + aPost_Width));
//                Log.e("====", String.valueOf(bPost_Y - aPost_Height+1)+String.valueOf("  ")+String.valueOf(aPost_Y + aPost_Height));


            }

            rm_list.clear();
            for (int i = 0; i < psys.size(); ) {
                if (psys.get(i).isOver()) {
                    psys.remove(i);
                    continue;
                } else {
                    psys.get(i).draw(canvas);
                    psys.get(i).update(16);
                }
                i++;
            }

        }

        private void drawButton(Canvas canvas, String msg, RectF rectF) {
            canvas.save();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                canvas.drawRoundRect(rectF, 50, 50, buttonPaint);
                paint.setColor(Color.DKGRAY);
                paint.setTextSize(70);
                canvas.drawText("Resume", myWidth / 2 - 120, myHeight / 2 + 430, paint);
            } else {
                canvas.drawRect(rectF, buttonPaint);
            }
            canvas.restore();
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (myOver) {
                if (buttonRect.contains(event.getRawX(), event.getRawY())) {
//                    psys.add(new ParticleSys(arrPart, Color.GREEN, event.getRawX(), event.getRawY(), new Runnable() {
//                        @Override
//                        public void run() {
//
//                        }
//                    }));
                    GameStart();
                }
                return true;
            }

            int eve = event.getAction();
//            targetY = myBall_Y - myBall_Up;

            switch (eve) {
                case MotionEvent.ACTION_DOWN:
                    targetY = 0;
//                    Log .e("============Down", myBall_Y + "====" + targetY);
                    return true;
                case MotionEvent.ACTION_UP:
                    targetY = 10000000;
//                    Log.e("============Up", myBall_Y + "====" + targetY);
                    break;
            }
            handler.sendEmptyMessage(0x123);
            return false;
        }


    }
}
